<template>
  <div class="upload-container">
    <el-upload
      action=""
      name="file"
      :multiple="multiple"
      :show-file-list="showList"
      :before-upload="beforeUpload"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :http-request="upload"
      :file-list="fileList"
      :drag="drag"
      with-credentials
    >
    <el-button type="primary">上传文件</el-button>
    </el-upload>
  </div>
</template>
<script lang="ts" setup>
import {ref,reactive,defineProps,withDefaults} from 'vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { success, confirm, error } from '/@/utils/msg'

interface IUpload {
  limit?:number,
  multiple?:boolean,
  drag?:boolean,
  showList?:boolean,
  fileList?:any
}

// 设置默认值
const props = withDefaults(defineProps<IUpload>(),{
  limit:1,
  multiple:false,
  drag:false,
  showList:true,
  fileList:[]
})

const beforeUpload = (file)=>{
  const typeList = ['image/jpeg', 'image/png', 'image/gif']
    const isTypeValid = typeList.includes(file.type)
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isTypeValid) {
      error('图片格式只能是 JPG/PNG/GIF!')
    }
    if (!isLt2M) {
      error('图片大小不能超过 2MB!')
    }
    return isTypeValid && isLt2M
}

// 上传成功
const handleUploadSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
  console.log(response,uploadFile)
}

// 上传报错
const handleUploadError = (err) => {
  error(err.message)
}

// 移除操作
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
} 

// 预览
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}

// 覆盖自动上传操作
const upload = ( UploadRequestOptions ) => {
  return UploadRequestOptions
}

defineExpose({
  handlePreview,
  handleRemove
})

</script>
<style>

</style>